import { useState } from 'react';
import { Button, Space, Form, Row, Col, Table, Select, Popconfirm } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryOccupyListParams, Occupy } from './services';
import { OccupyStatus, queryChargeList, updateStatus } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { enum2options } from '@/utils/enum2options';
import { minute2timeObj, parseOccupyFee, zeroFill } from '@/utils/common';
import { Access } from '@umijs/max';
import StationSelect from '@/components/StationSelect';
import type { OccupyFee } from './components/OccupyFee';
import SetRuleModal from './components/SetRuleModal';

const format = (fee: OccupyFee) => {
  const startTime = minute2timeObj(fee.startTime)
  const endTime = minute2timeObj(fee.endTime)

  return <div>{zeroFill(startTime.hour)}:{zeroFill(startTime.minute)}~{zeroFill(endTime.hour)}:{zeroFill(endTime.minute)} {fee.price}元/分钟</div>
}

const OccupyPage: React.FC<RoutePageProps> = () => {
  const [searchForm] = Form.useForm<QueryOccupyListParams>()
  const [searchParams, setSearchParams] = useState<QueryOccupyListParams>({
    pageNum: 1, pageSize: 10,
  })
  const list = useRequest(() => queryChargeList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: updateStatusSync } = useRequest(updateStatus, {manual: true})
  const [setModalRecord, setSetModalRecord] = useState<Occupy>()

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      stubGroupId: formValues.station?.[0]?.id,
      status: formValues.status,
      pageNum: 1,
    })
  }

  const openSetRuleModal = (record: Occupy) => {
    setSetModalRecord(record)
  }

  const closeSetRuleModal = (refresh: boolean) => {
    if (refresh) list.refresh()
    setSetModalRecord(undefined)
  }

  const columns: ColumnsType<Occupy> = [
    {
      title: '电站名称',
      dataIndex: 'stationName',
    },
    {
      title: '占用单价',
      dataIndex: 'feeInfo',
      render: val => {
        if (!val) return '--'
        const feeList = parseOccupyFee(val)
        return feeList.map(item => format(item))
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: val => val ? OccupyStatus[val] : '--'
    },
    {
      title: '免费时长',
      dataIndex: 'freeTime',
      width: 100,
      render: val => val ? `${val}分钟` : '--'
    },
    {
      title: '最大收费(元)',
      dataIndex: 'maxMoney',
      width: 120,
      render: val => val ? `${val}元` : '--'
    },
    {
      title: '生效时间',
      dataIndex: 'beginDay',
      render: (val, record) => {
        if (val && record.endDay) return <div>{dayjs(val).format('YYYY-MM-DD')}至{dayjs(record.endDay).format('YYYY-MM-DD')}</div>
        return '--'
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: val => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '--',
    },
    {
      title: '操作',
      key: 'operation',
      width: 100,
      fixed: 'right',
      render: (_, record) => {
        const { status, operatorId } = record
        return <Space>
          <Access accessible={status === OccupyStatus.启用 && !operatorId}>
            <Popconfirm
              title={`确定禁用规则吗？`}
              onConfirm={() => updateStatusSync({stubGroupId: record.stationId, status: OccupyStatus.禁用}).then(list.refresh)}
              okText="禁用"
              cancelText="取消"
            >
              <a>禁用</a>
            </Popconfirm>
          </Access>
          <Access accessible={status === OccupyStatus.禁用 && !operatorId}>
            <Popconfirm
              title={`确定启用规则吗？`}
              onConfirm={() => updateStatusSync({stubGroupId: record.stationId, status: OccupyStatus.启用}).then(list.refresh)}
              okText="启用"
              cancelText="取消"
            >
              <a>启用</a>
            </Popconfirm>
          </Access>
          <Access accessible={!operatorId}>
            <a onClick={() => openSetRuleModal(record)}>设置</a>
          </Access>
        </Space>
      }
    },
  ]
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form name='searchOccupyForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='场站' name='station'>
                  <StationSelect allowClear inline />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='状态' name='status'>
                  <Select placeholder='请选择' options={enum2options(OccupyStatus)} allowClear style={{width: '100%'}} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<Occupy>
          rowKey='orderId'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <SetRuleModal
        rule={setModalRecord}
        onCancel={closeSetRuleModal}
      />
    </div>
  );
};

export default OccupyPage;
